package h0829;

import java.util.LinkedList;
import java.util.List;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 判断链表是否回文
 * @date 2024/8/29 1:20
 */
public class JudgeIsPalindrome {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2, new ListNode(3, new ListNode(2, new ListNode(1))));
        System.out.println(isPalindrome2(head));
    }

    private static boolean isPalindrome(ListNode head) {
        LinkedList<ListNode> stack = new LinkedList<>();
        ListNode node = head;
        while (node != null) {
            stack.addLast(node);
            node = node.next;
        }
        while (head != null) {
            if (head.val != stack.peekLast().val) {
                return false;
            }
            head = head.next;
            stack.removeLast();
        }
        return true;
    }

    private static boolean isPalindrome2(ListNode head) {
        if (head!=null&&head.next==null){
            return true;
        }
        ListNode slow = head;
        ListNode fast = head;
        //快慢指针
        //无论怎么走，slow后面的总是后半部分
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //反转后半部分链表
        ListNode dummy = slow;
        ListNode p = dummy.next;
        ListNode q = p.next;
        while (p.next != null) {
            p.next = q.next;
            q.next = dummy.next;
            dummy.next = q;
            q = p.next;
        }
        ListNode node=dummy.next;
        while (node != null) {
            if (node.val != head.val) {
                return false;
            }
            node = node.next;
            head = head.next;
        }
        return true;
    }
}
